﻿namespace Atomic.Mvc.Filters
{
    using System;
    using System.Text;
    using System.Web.Mvc;

    using Atomic.Logging;

    /// <summary>
    /// ASP.NET MVC 异常处理。
    /// </summary>
    public class CustomHandleErrorAttribute : HandleErrorAttribute
    {
        /// <summary>
        /// 初始化 ASP.NET MVC 异常处理。
        /// </summary>
        public CustomHandleErrorAttribute()
        {
            this.Logger = LoggerFactory.Current.Create();
        }

        /// <summary>
        /// 日志工具。
        /// </summary>
        private ILogger Logger { get; set; }

        /// <summary>
        /// 异常处理。
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.Exception != null)
            {
                object uri = filterContext.HttpContext.Request.Url;

                string url = string.Empty;

                if (uri != null)
                {
                    url = uri.ToString();
                }

                Exception ex = filterContext.Exception.GetBaseException();

                StringBuilder text = new StringBuilder();

                text.AppendLine("异常地址：" + url);
                text.AppendLine("异常信息：" + ex.Message);

                this.Logger.Fatal(ex, text.ToString());
                //_logService.InsertSingleGlobalLog(LogEnum.LogType.Exception, ex.Message, url, ex.StackTrace);
            }

            base.OnException(filterContext);
        }
    }
}